package com.wlstock.funi.ui;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.webkit.WebSettings;
import android.webkit.WebSettings.LayoutAlgorithm;
import android.webkit.WebSettings.ZoomDensity;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TableRow;
import android.widget.TextView;

import com.android.volley.VolleyError;
import com.em.baselistener.OnBackListener;
import com.em.baselistener.OnMoreListener;
import com.em.baselistener.OnTitleClickListener;
import com.em.widget.view.SelectPopUpWindow.onPopViewListener;
import com.fourmob.datetimepicker.date.DatePickerDialog;
import com.fourmob.datetimepicker.date.DatePickerDialog.OnDateSetListener;
import com.wlstock.funi.R;
import com.wlstock.funi.adapter.WenGuScrollAdapter;
import com.wlstock.funi.adapter.WenGuScrollAdapter.onRowClick;
import com.wlstock.funi.app.FundAsyTask;
import com.wlstock.funi.app.FundAsyTask.TaskLitener;
import com.wlstock.funi.app.FundAsyTask.TaskResultListener;
import com.wlstock.funi.dao.StrategyDao;
import com.wlstock.funi.model.OperateModel;
import com.wlstock.funi.model.SelfFundModel;
import com.wlstock.funi.model.StrategyModel;
import com.wlstock.funi.request.EventBusConstants;
import com.wlstock.funi.request.NetWorkListener;
import com.wlstock.funi.request.WenGuRequest;
import com.wlstock.funi.utils.StockUtils;
import com.wlstock.funi.utils.ToastUtils;
import com.wlstock.funi.widget.TradeSelector;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import info.zhangxing.ZPagedHScrollTable;

public class ScrollTableActivity extends FundBaseFragmentActivity implements NetWorkListener, OnBackListener, OnMoreListener, onPopViewListener, OnClickListener, onRowClick, OnCheckedChangeListener, OnTitleClickListener {

	private static final String KEY_TITLE = "title";
	private static final String KEY_RESULT = "result";
	private static final String KEY_COUNT = "count";
	private static final String SLG1 = "SLG1";
	public ZPagedHScrollTable scroll_table ;
	public WenGuScrollAdapter wenGuScrollAdapter;
	public TextView tv_search_count;
	private WenGuRequest wgRequest;
	private EditText ed_search_key;
	private Button btn_search;
	private List<SelfFundModel> reqFundModels;
	private WebView webview_scrolltable;
	private boolean isTableVisible;
	private TextView tv_add_prifixtime;
	private TextView tv_end_time;
	private TextView tv_begin_time;
	private CheckBox cb_is_add_prefix;
	private DatePickerDialog dayPicker;
	private DateSelecetListener dateSelecetListener;

	public LinearLayout layout_stategy_time;
	public LinearLayout layout_search_time;
	private String requestKey;
	private String strategyKey = "";

	@Override
	protected void onCreate(Bundle savedInstanceState) {

		requestWindowFeature(Window.FEATURE_NO_TITLE);
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_scroll_table);
		setTitle(getResources().getString(R.string.title_scrolltable));
		onBackClick(this);
		onMoreClick(this);
		onTitleClick(this);

		ed_search_key = (EditText) findViewById(R.id.ed_search_key);
		ed_search_key.addTextChangedListener(new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
			}

			@Override
			public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
			}

			@Override
			public void afterTextChanged(Editable ed) {
				requestKey = ed.toString();
			}
		});
		tv_search_count = (TextView) findViewById(R.id.tv_search_count);

		btn_search = (Button) findViewById(R.id.btn_search);
		btn_search.setOnClickListener(this);

		scroll_table = (ZPagedHScrollTable) findViewById(R.id.scroll_table);
		scroll_table.setPageSize(15);

		webview_scrolltable = (WebView) findViewById(R.id.webview_scrolltable);
		setwebViewSettings(webview_scrolltable);

		wgRequest = new WenGuRequest();
		wgRequest.netWorkListener = this;

		layout_search_time = (LinearLayout) findViewById(R.id.layout_search_time);
		layout_stategy_time = (LinearLayout) findViewById(R.id.layout_stategy_time);

		findViewById(R.id.btn_list).setOnClickListener(this);
		findViewById(R.id.btn_strategy).setOnClickListener(this);

		Calendar calInstance = Calendar.getInstance();
		dateSelecetListener = new DateSelecetListener();
		dayPicker = DatePickerDialog.newInstance(dateSelecetListener, calInstance.get(Calendar.YEAR), calInstance.get(Calendar.MONTH), calInstance.get(Calendar.DAY_OF_MONTH));

		tv_add_prifixtime = (TextView) findViewById(R.id.tv_add_prifixtime);
		tv_add_prifixtime.setOnClickListener(this);
		cb_is_add_prefix = (CheckBox) findViewById(R.id.cb_is_add_prefix);
		cb_is_add_prefix.setOnCheckedChangeListener(this);

		tv_end_time = (TextView) findViewById(R.id.tv_end_time);
		tv_begin_time = (TextView) findViewById(R.id.tv_begin_time);
		tv_end_time.setOnClickListener(this);
		tv_begin_time.setOnClickListener(this);

		setTableVisible(true);
	}

	/**
	 * 搜索表格是否可见
	 * @param isTableVisible
	 */
	public void setTableVisible(boolean isTableVisible) {
		this.isTableVisible = isTableVisible;
		if (isTableVisible) {
			scroll_table.setVisibility(View.VISIBLE);
			layout_search_time.setVisibility(View.VISIBLE);
			webview_scrolltable.setVisibility(View.GONE);
			layout_stategy_time.setVisibility(View.GONE);

			if (isTextNullOrEmpty(tv_add_prifixtime)) {
				tv_add_prifixtime.setText(new SimpleDateFormat("M月dd日").format(new Date()));
			}
		}else {
			webview_scrolltable.setVisibility(View.VISIBLE);
			layout_stategy_time.setVisibility(View.VISIBLE);
			scroll_table.setVisibility(View.GONE);
			layout_search_time.setVisibility(View.GONE);

			if (isTextNullOrEmpty(tv_begin_time)) {
				tv_begin_time.setText("2013-01-01");
			}

			if (isTextNullOrEmpty(tv_end_time)) {
				tv_end_time.setText(new SimpleDateFormat("yyyy-MM-dd").format(new Date()));
			}
		}
	}

	private boolean isTextNullOrEmpty(TextView tv) {
		if (tv.getText()==null || tv.getText().toString().isEmpty()) {
			return true;
		}
		return false;
	}

	@Override
	public void onErrorResponse(VolleyError error, EventBusConstants eventCode) {

	}


	@Override
	public void onErrorResponse(VolleyError error, String eventCode) {
		if (SLG1.equals(eventCode)) {

		}
	}

	@Override
	public void onResponse(String response, EventBusConstants eventCode) {
	}


	@Override
	public void onResponse(String response, String eventCode) {
		if (SLG1.equals(eventCode)) {

			FundAsyTask<String, Void, HashMap<String, Object>> task = new FundAsyTask<String, Void, HashMap<String,Object>>();
			task.backListener = new TaskLitener<String, HashMap<String,Object>>() {

				@Override
				public HashMap<String, Object> doInBackground(String... params) {
					return StockUtils.parseWenguTableData(params[0]);
				}
			};
			task.resultListener = new TaskResultListener<HashMap<String,Object>>() {

				@Override
				public void onPostResult(HashMap<String, Object> result) {
					configTable(result);
				}
			};
			task.execute(response);
		}
	}

	private void configTable(HashMap<String, Object> result) {
		if (result!=null) {
			String[] titles = (String[]) result.get(KEY_TITLE);
			ArrayList<ArrayList<String>> results = (ArrayList<ArrayList<String>>) result.get(KEY_RESULT);

			if (results!=null) {
				tv_search_count.setText("共"+result.get(KEY_COUNT)+"条");
			}

			wenGuScrollAdapter = null;
			wenGuScrollAdapter = new WenGuScrollAdapter(titles, results);
			wenGuScrollAdapter.onRowClickListener = this;
			scroll_table.setAdapter(wenGuScrollAdapter);
			scroll_table.refreshTable();
		}else {
			tv_search_count.setText("此结果无数据返回");

		}
	}

	@Override
	public void onBackClick(View v) {
		this.finish();
	}

	@Override
	public void onMoreClick(View v) {
		showPopUpView(getMenuList(), this);
	}

	public List<Map<String, Object>> getMenuList() {
		ArrayList<Map<String, Object>> menus = new ArrayList<Map<String,Object>>();
		Map<String, Object> item1 = null;
		List<StrategyModel> straModels = StrategyDao.getInstance(this).queryAll();
		for (int i = 0; i < straModels.size(); i++) {
			item1 = new HashMap<String, Object>();
			item1.put("name", straModels.get(i).getShortName());
			menus.add(item1);

		}

		item1 = new HashMap<String, Object>();
		item1.put("name", getResources().getString(R.string.pop_title_add_sg));
		menus.add(item1);
		return menus;
	}

	@Override
	public void onViewSelectListener(String titleTxt) {
		if (titleTxt.equals(getResources().getString(R.string.pop_title_add_sg))) {
			View view_add = getLayoutInflater().inflate(R.layout.dialog_stategy_add, null);
			final EditText ed_strategy_short = (EditText) view_add.findViewById(R.id.ed_strategy_short);
			final EditText ed_strategy_full_value = (EditText) view_add.findViewById(R.id.ed_strategy_full_value);
			final EditText ed_strategy_url = (EditText) view_add.findViewById(R.id.ed_strategy_url);
			new AlertDialog.Builder(this).setTitle("增加策略").setView(view_add).setPositiveButton("确定", new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface arg0, int arg1) {
					if (ed_strategy_short.getText().toString().isEmpty() || ed_strategy_full_value.getText().toString().isEmpty()) {
						return;
					}
					StrategyModel strategyModel = new StrategyModel();
					strategyModel.setShortName(ed_strategy_short.getText().toString());
					strategyModel.setFullName(ed_strategy_full_value.getText().toString());
					strategyModel.setAppendURL(ed_strategy_url.getText().toString());
					StrategyDao.getInstance(ScrollTableActivity.this).createOrUpdate(strategyModel);
				}
			}).setNegativeButton("取消", null).show();
		}else {
			strategyKey = titleTxt;
			requestKey =  StrategyDao.getInstance(this).queryStraByShortName(titleTxt);
			wgRequest.request(requestKey, SLG1);
			ed_search_key.setText(requestKey);
		}
	}


	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btn_search:
			setTableVisible(true);
			requestWGDatas();
			break;
		case R.id.btn_list:
			setTableVisible(true);
			requestWGDatas();
			break;
		case R.id.btn_strategy:
			setTableVisible(false);
			requestWGDatas();
			break;
		case R.id.tv_add_prifixtime:
			dateSelecetListener.setView(tv_add_prifixtime);
			showDatePicker();
			break;
		case R.id.tv_begin_time:
			dateSelecetListener.setView(tv_begin_time);
			showDatePicker();
			break;
		case R.id.tv_end_time:
			dateSelecetListener.setView(tv_end_time);
			showDatePicker();
			break;
		default:
			break;
		}

	}

	private void showDatePicker() {
		dayPicker.setCloseOnSingleTapDay(true);
		dayPicker.setYearRange(2014, 2017);
		if (!dayPicker.isAdded()) {
			dayPicker.show(getSupportFragmentManager(), "DAY_PICKER");
		}

	}

	private void requestWGDatas() {
		if (ed_search_key.getText().toString()!=null && !ed_search_key.getText().toString().isEmpty()) {
			if (isTableVisible) {
				loadTable();
			}else {
				loadWebView();
			}
		}else {
			ToastUtils.showMiddleMsg(this, "请输入策略");
		}
	}

	private void loadWebView() {
//		http://search.10jqka.com.cn/regression/result?stockHoldCount=2&fallIncome=5&lowerIncome=8&upperIncome=10&fell=0.001&endDate=2016-05-11&startDate=2013-01-01&daysForSaleStrategy=2%2C3%2C4%2C5%2C10%2C20%2C30&
		try {
			String keyEncode ="query=" + URLEncoder.encode(ed_search_key.getText().toString(),"utf-8")+"&";
			String time   = "endDate="+tv_end_time.getText().toString()+"&startDate="+tv_begin_time.getText().toString();
			String urlStr = "http://search.10jqka.com.cn/regression/result?stockHoldCount=2&fallIncome=5&lowerIncome=8&upperIncome=10&fell=0.001&daysForSaleStrategy=2%2C3%2C4%2C5%2C10%2C20%2C30&qs=backtest_optimize_menu1&"+keyEncode+time;
			webview_scrolltable.loadUrl(urlStr);
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	private void loadTable() {
		String key = addOrReset(cb_is_add_prefix.isChecked());
		ed_search_key.setText(key);
		wgRequest.request(key, SLG1);
	}

	@Override
	public void onCheckedChanged(CompoundButton arg0, boolean isChecked) {
		String key = addOrReset(isChecked);
		ed_search_key.setText(key);
	}

	private String addOrReset(boolean isChecked) {
		if (!isChecked && requestKey!=null && !requestKey.isEmpty()) {
			return requestKey;
		}
		if (requestKey!=null && !requestKey.isEmpty()) {
			String[] item = requestKey.split(";");
			String key = "";
			if (item!=null) {
				for(int i = 0 ; i < item.length; i++){
					item[i] = tv_add_prifixtime.getText().toString()+item[i];
					key += item[i]+";";
				}
				return key;
			}else {
				return requestKey;
			}
		}else {
			return "";
		}

	}

	@Override
	public void rowClick(TableRow row, int position) {
		int count = row.getChildCount();
		for (int i = 0; i < count; i++) {
			View cView = row.getChildAt(i);
			if (cView instanceof TextView) {
				String rowTV = ((TextView)cView).getText().toString();
				String parseRowResult = StockUtils.parseRow(rowTV);
				if (parseRowResult!=null) {
					TradeSelector selector = new TradeSelector(this, "", parseRowResult);
					selector.show(OperateModel.TradeType_BUY);
				}
			}
		}

	}


	@SuppressWarnings("deprecation")
	public void setwebViewSettings(WebView view){
		WebSettings webSettings = view.getSettings();
		// User settings
		webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
		webSettings.setUseWideViewPort(true);// 关键点
		webSettings.setLayoutAlgorithm(LayoutAlgorithm.SINGLE_COLUMN);
		webSettings.setDisplayZoomControls(false);
		webSettings.setJavaScriptEnabled(true); // 设置支持javascript脚本
		webSettings.setAllowFileAccess(true); // 允许访问文件
		webSettings.setBuiltInZoomControls(true); // 设置显示缩放按钮
		webSettings.setSupportZoom(true); // 支持缩放
		webSettings.setLoadWithOverviewMode(true);

		DisplayMetrics metrics = new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getMetrics(metrics);
		int mDensity = metrics.densityDpi;

		if (mDensity == 240) {
			webSettings.setDefaultZoom(ZoomDensity.FAR);
		} else if (mDensity == 160) {
			webSettings.setDefaultZoom(ZoomDensity.MEDIUM);
		} else if (mDensity == 120) {
			webSettings.setDefaultZoom(ZoomDensity.CLOSE);
		} else if (mDensity == DisplayMetrics.DENSITY_XHIGH) {
			webSettings.setDefaultZoom(ZoomDensity.FAR);
		} else if (mDensity == DisplayMetrics.DENSITY_TV) {
			webSettings.setDefaultZoom(ZoomDensity.FAR);
		} else {
			webSettings.setDefaultZoom(ZoomDensity.MEDIUM);
		}

		/**
		 * 用WebView显示图片，可使用这个参数 设置网页布局类型： 1、LayoutAlgorithm.NARROW_COLUMNS ：
		 * 适应内容大小 2、LayoutAlgorithm.SINGLE_COLUMN:适应屏幕，内容将自动缩放
		 */
		webSettings.setLayoutAlgorithm(LayoutAlgorithm.NARROW_COLUMNS);
	}


	public class DateSelecetListener implements OnDateSetListener{

		private TextView tv;

		public void setView(TextView tv){
			this.tv = tv;
		}

		@Override
		public void onDateSet(DatePickerDialog datePickerDialog, int year, int month, int day) {
			month=month+1;
			if (tv!=null) {
				switch (tv.getId()) {
				case R.id.tv_add_prifixtime:
					tv.setText(month+"月"+day+"日");
					break;
				case R.id.tv_begin_time:
				case R.id.tv_end_time:
					SimpleDateFormat formater = new SimpleDateFormat("yyyy-MM-dd");
					try {
						tv.setText(formater.format(formater.parse(year+"-"+month+"-"+day)));
					} catch (ParseException e) {
						tv.setText(formater.format(new Date()));
						e.printStackTrace();
					}
					break;
				default:
					break;
				}
			}

		}

	}

	@Override
	public void onTitleClick(View v) {
		if (strategyKey==null || strategyKey.isEmpty()) {
			return;
		}
		String url = StrategyDao.getInstance(this).querAppendUrlByShortName(strategyKey);
		if (url !=null && !url.isEmpty()) {
			webview_scrolltable.loadUrl(url);
		}
	}


}
